package com.qingzhou.file.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.qingzhou.file.config.FileConfig;
import com.qingzhou.common.core.web.api.ApiCodes;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.cloud.CloudClient;
import org.noear.solon.cloud.model.Media;
import org.noear.solon.core.handle.Result;
import org.noear.solon.core.handle.UploadedFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传（支持本地、阿里云、七牛云、minio等，想使用哪种，在 pom.xml中解开它的注释并注释掉其它的）
 * @author xm
 */
@Component
public class FileService {

    @Inject
    FileConfig fileConfig;

    /**
     * 单文件上传
     * @param file
     * @return
     */
    public Result uploadFile(UploadedFile file) {
        try {
            if(file == null || file.isEmpty()) {
                throw ApiCodes.CODE_400("文件为空");
            }
            String key = DateUtil.today() + "/" + file.getName();
            // 上传文件
            return upload(key, file);
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    /**
     * 多文件上传
     * @param file
     * @return
     */
    public Result uploadFiles(UploadedFile[] file) {
        try {
            if(file == null || file.length == 0) {
                throw ApiCodes.CODE_400("文件为空");
            }
            for (UploadedFile uploadedFile : file) {
                if(uploadedFile == null || uploadedFile.isEmpty()) {
                    throw ApiCodes.CODE_400("文件为空");
                }
            }
            List<String> list = new ArrayList<>();
            String key = DateUtil.today() + "/";
            for (UploadedFile uploadedFile : file) {
                // 上传文件
                Result result = upload(key + uploadedFile.getName(), uploadedFile);
                if(result.getCode() == Result.SUCCEED_CODE) {
                    list.add(String.valueOf(result.getData()));
                } else {
                    throw ApiCodes.CODE_400("文件上传失败");
                }
            }
            return Result.succeed(list);
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    /**
     * 上传
     * @param key
     * @param file
     */
    private Result upload(String key, UploadedFile file) {
        if(fileConfig.getMaxSize() != -1 && fileConfig.isLimitSize(file.getContentSize())) {
            throw ApiCodes.CODE_400("请上传 " + fileConfig.getMaxSize() + "M 以内的文件");
        }
        if(!StrUtil.containsAny(file.getExtension(), fileConfig.getFileType())) {
            throw ApiCodes.CODE_400("不支持此类文件上传");
        }
        return CloudClient.file().put(key, new Media(file.getContent(), Utils.mime(file.getName())));
    }

}
